function MyPromise(executor) {
    const PENDING = "pending";
    const FULFILLED = "fulfilled";
    const REJECTED = "rejected";

    this.state = PENDING;
    this.value = undefined;
    this.reason = undefined;

    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];

    const resolve = (newValue) => {
        if (this.state !== PENDING) return;
        this.state = FULFILLED;
        this.value = newValue;
        this.onFulfilledCallbacks.forEach((cb) => cb(this.value));
    };

    const reject = (error) => {
        if (this.state !== PENDING) return;
        this.state = REJECTED;
        this.reason = error;
        this.onRejectedCallbacks.forEach((cb) => cb(this.reason));
    };

    try {
        executor(resolve, reject);
    } catch (error) {
        reject(error);
    }
}

MyPromise.prototype.then = function (onFulfilled, onRejected) {
    const promise = new MyPromise((resolve, reject) => {
        this.onFulfilledCallbacks.push(() => {
            try {
                const result = onFulfilled(this.value);
                resolve(result);
            } catch (error) {
                reject(error);
            }
        });
        this.onRejectedCallbacks.push(() => {
            try {
                const result = onRejected(this.reason);
                resolve(result);
            } catch (error) {
                reject(error);
            }
        });
    });
    return promise;
};

MyPromise.prototype.catch = function (onRejected) {
    return this.then(undefined, onRejected);
};

MyPromise.prototype.finally = function (onFinally) {
    return this.then(
        (value) =>
            MyPromise.resolve().then(() => {
                onFinally();
                return value;
            }),
        (reason) =>
            MyPromise.resolve().then(() => {
                onFinally();
                throw reason;
            }),
    );
};

// 静态方法
MyPromise.resolve = function (value) {
    return new MyPromise((resolve) => resolve(value));
};

MyPromise.reject = function (reason) {
    return new MyPromise((_, reject) => reject(reason));
};

// 使用示例
function asyncTask() {
    return new MyPromise((resolve, reject) => {
        setTimeout(() => {
            resolve("Task completed");
        }, 1000);
    });
}

asyncTask()
    .then((result) => console.log(result))
    .catch((error) => console.error(error))
    .finally(() => console.log("Operation complete"));
